package org.javaboy.rpc_server.controller;

import org.javaboy.rpc_server.config.RabbitConfig;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class RpcServer {

    @Autowired
    RabbitTemplate rabbitTemplate;

    @RabbitListener(queues = RabbitConfig.SEND_MSG_QUEUE)
    public void handleMsg(Message message) {
        //获取发送来的消息
        String s = new String(message.getBody());
        //获取发送来的消息的 correlationId，这个 correlationId 要手动放在返回的消息中，否则无法匹配
        String correlationId = message.getMessageProperties().getCorrelationId();
        Message replyMsg = MessageBuilder.withBody(("rpc server receive:" + s).getBytes()).build();
        rabbitTemplate.sendAndReceive(RabbitConfig.RPC_EXCHANGE, RabbitConfig.REPLY_MSG_QUEUE, replyMsg, new CorrelationData(correlationId));
    }
}
